package com.sugon.modules.device.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.sugon.dao.DevMaintenanceTicketDao;
import com.sugon.entity.*;
import com.sugon.modules.base.consts.SysApproveStatusConst;
import com.sugon.modules.device.consts.DevMaintenanceTicketStatus;
import com.sugon.modules.device.consts.DeviceLeaveRecordStatus;
import com.sugon.modules.device.consts.DeviceStatus;
import com.sugon.modules.device.model.vo.DevSparepartCorrelationParamVO;
import com.sugon.modules.device.model.vo.DeviceApproveParamVO;
import com.sugon.modules.device.service.IDeviceMaintenancePlanManager;
import com.sugon.modules.device.service.IDeviceManager;
import com.sugon.modules.sys.consts.ProcessApproveStatus;
import com.sugon.modules.sys.consts.ProcessProgressStatus;
import com.sugon.service.*;
import com.sugon.utils.ProcessInfoEnum;
import org.apache.shiro.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author ： YuXD
 * @description： 设备业务Manager实现类
 * @date ： 2020-08-07 下午 6:51
 * @version: 1.0
 */
@Service
public class DeviceManagerImpl implements IDeviceManager {

    @Autowired
    private DeviceInfoService deviceInfoService;
    @Autowired
    private DevLeaveRecordService devLeaveRecordService;
    @Autowired
    private DevChangeRecordService devChangeRecordService;
    @Autowired
    private SparePartDevService sparePartDevService;
    @Autowired
    private SysProcessInfoService sysProcessInfoService;
    @Autowired
    private SysMsgService sysMsgService;
    @Autowired
    private DevMaintenanceTicketDao devMaintenanceTicketDao;
    @Resource
    private DevMaintenanceTicketService devPmTicketService;
    @Autowired
    private IDeviceMaintenancePlanManager deviceMaintenancePlanManager;

    /**
     * @param devSparepartCorrelationParam 设备-备件关联参数
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addDevSparepartCorrelation(DevSparepartCorrelationParamVO devSparepartCorrelationParam) {
        String devId = devSparepartCorrelationParam.getDevId();
        List<String> sparePartIdList = devSparepartCorrelationParam.getSparePartIdList();
        if (CollectionUtil.isNotEmpty(sparePartIdList)) {
            SparePartDevEntity sparePartDev;
            for (String sparePartId : sparePartIdList) {
                // 校验设备和备件是否已存在关联
                if (!sparePartDevService.checkIsExists(devId, sparePartId)) {
                    sparePartDev = new SparePartDevEntity(devId, sparePartId);
                    if (sparePartDevService.save(sparePartDev) > 0) {
                        //添加审核 消息提醒
                        sysProcessInfoService.saveProcessInfo(sparePartDev.getId(), ProcessInfoEnum.DEV_SBQD, 0, null);
                        SysMsgEntity sysMsgEntity = new SysMsgEntity();
                        sysMsgEntity.setDataId(sparePartDev.getId());
                        sysMsgEntity.setDataUrl("../sys/devAddReplace.html?id=" + sparePartDev.getDevId());
                        // 添加审批事项
                        sysMsgService.addApproveItem(ProcessInfoEnum.DEV_SBQD, sysMsgEntity, 0);
                    }
                }
            }
        }
        return true;
    }

    /**
     * @param devLeaveApplyList 设备闲置申请列表
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addDevLeaveApply(List<DevLeaveRecordEntity> devLeaveApplyList) {
        DeviceInfoEntity deviceInfo;
        DevLeaveRecordEntity devLeaveRecord;
        // 1、生成设备闲置记录申请
        for (DevLeaveRecordEntity rootDevLeaveRecord : devLeaveApplyList) {
            deviceInfo = deviceInfoService.queryObject(rootDevLeaveRecord.getId());
            Assert.notNull(deviceInfo, "设备信息不存在!");
            devLeaveRecord = new DevLeaveRecordEntity();
            //闲置记录实体添加数据
            devLeaveRecord.setDevCode(deviceInfo.getDevCode());
            devLeaveRecord.setDevName(deviceInfo.getDevName());
            devLeaveRecord.setDevId(deviceInfo.getId());
            devLeaveRecord.setStartDate(deviceInfo.getCreateDate());
            devLeaveRecord.setAssertCode(deviceInfo.getFirmNo());
            devLeaveRecord.setDevModel(deviceInfo.getReserve1());
            devLeaveRecord.setDevNum(1);
            devLeaveRecord.setReson(rootDevLeaveRecord.getReson());
//            devLeaveRecord.setOrigVal(deviceInfo.getOriginVal());
            devLeaveRecord.setNetVal(rootDevLeaveRecord.getNetVal());
            devLeaveRecord.setAddress(deviceInfo.getDevFarmName());
            devLeaveRecord.setUseUnit(deviceInfo.getDevFarmName());
            devLeaveRecord.setDevModel(deviceInfo.getReserve1());
            devLeaveRecord.setWorkshop(deviceInfo.getDevFarm());
            devLeaveRecord.setStatus(DeviceLeaveRecordStatus.APPROVING);
            int rows = devLeaveRecordService.save(devLeaveRecord);
            if (rows > 0) {
                // 更新设备状态为闲置审核中
                deviceInfoService.updateStatus(deviceInfo.getId(), DeviceStatus.LEAVE_APPROVING);
            }
        }
        return true;
    }

    /**
     * @param devLeaveRecordIds 设备闲置申请记录ID列表，每个ID之间用逗号分隔
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean batchReviewDevLeaveApply(String[] devLeaveRecordIds) {
        DeviceInfoEntity deviceInfo;
        String devId;
        for (String devLeaveApplyRecordId : devLeaveRecordIds) {
            // 获取设备闲置记录
            DevLeaveRecordEntity devLeaveRecord = devLeaveRecordService.queryObject(devLeaveApplyRecordId);
            if (devLeaveRecord == null) {
                continue;
            }
            if (devLeaveRecordService.updateStatus(devLeaveApplyRecordId, DeviceLeaveRecordStatus.LEAVING)) {
                devId = devLeaveRecord.getDevId();
                // 更新设备状态为闲置
                deviceInfoService.updateStatus(devId, DeviceStatus.LEAVE);
                // 生成设备(变更)台账
                deviceInfo = deviceInfoService.queryObject(devId);
                if (deviceInfo != null) {
                    DevChangeRecordEntity changeRecordEntity = new DevChangeRecordEntity();
                    changeRecordEntity.setDevProductName(deviceInfo.getDevProductName());
                    changeRecordEntity.setDevCode(deviceInfo.getDevCode());
                    changeRecordEntity.setDevName(deviceInfo.getDevName());
                    changeRecordEntity.setSubFactory(deviceInfo.getDevFactories());
                    changeRecordEntity.setWorkshop(deviceInfo.getDevFarm());
                    changeRecordEntity.setDevProceName(deviceInfo.getDevProceName());
                    changeRecordEntity.setDevProceNo(deviceInfo.getDevProceNo());
                    changeRecordEntity.setDevStatus(Integer.parseInt(DeviceStatus.LEAVE));
                    changeRecordEntity.setDevModel(deviceInfo.getReserve1());
                    changeRecordEntity.setOrigVal(devLeaveRecord.getOrigVal());
                    changeRecordEntity.setNetVal(devLeaveRecord.getNetVal());
                    changeRecordEntity.setReson(devLeaveRecord.getReson());
                    changeRecordEntity.setRemark(devLeaveRecord.getReson());
                    devChangeRecordService.save(changeRecordEntity);
                }
                // 标识设备维护计划中，所有当前设备的维护项不可用
                deviceMaintenancePlanManager.disablePlanItemByDevId(devId, "当前设备闲置，禁用所有维护计划项防止生成维护工单！");
                // 对于现有的执行中的工单 进行关闭操作
                List<DevMaintenanceTicketEntity> devPmTicketList = devPmTicketService.queryListByDevId(devId);
                if (CollectionUtil.isNotEmpty(devPmTicketList)) {
                    for (DevMaintenanceTicketEntity devPmTicket : devPmTicketList) {
                        // 只要PM工单未完成、延期完成、取消、关闭，就需要统一关闭掉
                        Integer status = devPmTicket.getStatus();
                        if (!NumberUtil.equals(status, DevMaintenanceTicketStatus.COMPLETE) && !NumberUtil.equals(status, DevMaintenanceTicketStatus.STOP) && !NumberUtil.equals(status, DevMaintenanceTicketStatus.DELAY_COMPLETE) && !NumberUtil.equals(status, DevMaintenanceTicketStatus.CANCEL)) {
                            devPmTicket.setStatus(DevMaintenanceTicketStatus.STOP);
                            devPmTicket.setRemark("当前设备闲置，维护工单终止！");
                            devPmTicketService.update(devPmTicket);
                        }
                    }
                }
            }
        }
        return true;
    }

    /**
     * @param deviceApproveParam 设备审核参数
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean batchApprove(DeviceApproveParamVO deviceApproveParam) {
        List<String> approveDeviceIdList = deviceApproveParam.getApproveDeviceIdList();
        int totalRows = 0;
        DeviceInfoEntity device;
        // 获取审核结果
        int approveStatus = deviceApproveParam.getStatus();
        for (String approveDeviceId : approveDeviceIdList) {
            device = deviceInfoService.queryObject(approveDeviceId);
            org.springframework.util.Assert.notNull(device, "设备信息不存在，请确认！");
            device.setReserve4(approveStatus + "");
            int rows = deviceInfoService.update(device);
            if (rows > 0) {
                totalRows += rows;
                // 生成成审核通过提示消息
                SysMsgEntity sysMsgEntity = new SysMsgEntity();
                sysMsgEntity.setDataUrl("../sys/deviceinfo.html?Id=" + device.getId());
                sysMsgEntity.setUserId(device.getCreateUser());
                sysMsgEntity.setDataType(ProcessInfoEnum.DEV_SBQD);
                sysMsgEntity.setDataId(device.getId());
                // 如果审核通过
                if (approveStatus == SysApproveStatusConst.PASSED) {
                    sysProcessInfoService.saveProcessInfo(null, device.getId(), ProcessInfoEnum.DEV_SBQD, ProcessApproveStatus.PASSED_WITH_APPROVE, null, deviceApproveParam.getRemark(), ProcessProgressStatus.END);
                    sysMsgEntity.setRemark(StrUtil.format(ProcessInfoEnum.DEV_SBQD.getPassedMsgTemplate()));
                    sysMsgEntity.setDataFlag(ProcessProgressStatus.END + "");
                } else if (approveStatus == SysApproveStatusConst.NOT_PASSED) {
                    // 生成备件审核未通过流程信息
                    sysProcessInfoService.saveProcessInfo(null, device.getId(), ProcessInfoEnum.DEV_SBQD, approveStatus, null, deviceApproveParam.getRemark(), ProcessProgressStatus.ING);
                    // 1、给备件创建用户生成提示消息
                    sysMsgEntity.setRemark(StrUtil.format(ProcessInfoEnum.DEV_SBQD.getNotPassedMsgTemplate(), device.getDevName(), deviceApproveParam.getRemark()));
                }
                // 保存消息
                sysMsgService.addApproveItem(ProcessInfoEnum.DEV_SBQD, sysMsgEntity, 0);
            }
        }
        return totalRows == approveDeviceIdList.size();
    }

}
